<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>main</title>
<jsp:include page="../head.jsp" />
<style>
.tdSearch{background-color:#FFF398}
</style>
<script type="text/javascript">

	function save(){
		if($("#roleSelect").val()==0){
			j_tip("还没有选择角色！", 'error');
		}else{
			$(".hiddenRoleId").val($("#roleSelect").val());
			var str="";
			$(":checkbox").each(function(i){
				if(this.checked){
					str+=this.value+",";
				}
			});
			if(str==""){
				j_tip("你没有给该角色分配任何权限！", 'error');
			}else{
				str=str.substring(0,str.length-1);
				$(".hiddenString").val(str);
				xbox.load("loading");	
				$("#refreshForm").ajaxSubmit(function(){
					j_tip("该角色权限保存成功！", 'success');
					xbox.ready("loading");	
				});
			}
		}
		
		
	}
	function turnBack(){
		xbox.load("loading");
	   $("#refreshForm").submit();
	}
	
	function changeSelect(){
		var selectRoleId=$("#roleSelect").val();
		var checkBoxes = $(":checkbox");//只查询一次所有checkbox
		checkBoxes.attr("checked",false).prop("disabled","");
		xbox.load("loading");
		$.ajax({
			url			:"<%=path%>/roleauthority/roleauthorityAjax_queryRoleAuthority_msgAction.action",
			type 		: "POST",
			dataType 	: "json",
			data		: {
				"menuAuthorityRoleId" : selectRoleId
			},
			success 	: function(data) {
				var array=data.split("#");
				var arrayStr=null;
				var menu = 0;//记录完全控制，优化效率
				for(var i=0;i<array.length;i++){
					arrayStr=array[i].split(",");
					if(menu == arrayStr[0])//如果完全控制已经选中，则子项不需要设置
						continue;
					var checkBox = checkBoxes.filter("#"+array[i].replace(",","n"));//最重要的优化，从checkbox中通过ID获取，效率杠杠滴
					checkBox.attr("checked",true);
					if(arrayStr[1]==1){//完全控制选中所有子项
						menu = arrayStr[0];
						checkBox.parents("tr:first").find(":checkbox").attr("checked",true);
					}
				}
				xbox.ready("loading");
				j_tip("权限载入成功!", 'success');
			},
			error		:function(){
				xbox.alert("数据正在提交，请稍候，或检查您的网络环境,确保其连接正常！");
			}
		});
		
	}
	
	function checkboxSelect(menuId,authorityNo,obj){
		if($("#roleSelect").val()==0){
			addError($("#roleSelect"),"请先选择用户角色.");
			$(obj).prop("checked","");
			return false;
		}
		var parent = $(obj).parents("tr:first");
		if(authorityNo=="0001"){
			var value = "checked"
			if($(obj).prop("checked")==false)
				value = "";
			parent.find(":checkbox").prop("checked",value)
			if(parent.attr("pid")=="0"){
				//父级菜单
				$("tr[pid='"+parent.attr("mid")+"'] :checkbox").prop("checked",value);
			}else if($(obj).prop("checked")==false){
				$("tr[mid='"+parent.attr("pid")+"']:first :checkbox[code='0001']:first").prop("checked","");
			}
		}else{
			if($(obj).prop("checked")==false){
				parent.find(":checkbox[code='0001']:first").prop("checked","");
				if(parent.attr("pid")!="0"){
					//找到父级菜单，把完全控制取消了
					$("tr[mid='"+parent.attr("pid")+"']:first :checkbox[code='0001']:first").prop("checked","");
				}
			}
		}
	}
	
	$(function(){
		$("html:first,body:first").css("overflow","hidden");
		$("tr[pid]").each(function(){
			var pid = $(this).attr("pid");
			if(pid=="0"){
				var menuId = $(this).attr("mid");
				if($("tr[pid='"+menuId+"']:first").size()==1){
					//存在子项，可以关闭展开
					$(this).find("span:first").before('<span title="收起" action="'+menuId+'" style="font-family:@新宋体;float:left;cursor: pointer;">↑↑</span>');
				}
			}else{
				var prev = $(this).prev();
				//判断是否需要挪位置
				if(pid != prev.attr("mid") && pid != prev.attr("pid")){
					var lastTr = null;
					$("tr[pid='"+pid+"']").each(function(){
						//找到最后一个正确的子tr
						prev = $(this).prev();
						if(pid == prev.attr("pid") || pid == prev.attr("mid")){
							lastTr=$(this);
						}else{
							return false;
						}
					});
					if(lastTr==null)
						lastTr = $("tr[mid='"+pid+"']:first");
					if(lastTr!=null && lastTr.size()==1)
						$(this).insertAfter(lastTr);
				}
			}
		});
		var tableHeight= $("table:first").height();
		$("#divScroll").width($("body:first").width()-10).height($(window).height()-tableHeight-5).fadeIn(200);
		$("span[action]").click(function(){
			var title = $(this).attr("title");
			if(title=="收起"){
				$(this).prop("title","展开").html("↓↓");
				$("tr[pid='"+$(this).attr("action")+"']").hide();
			}else{
				$(this).prop("title","收起").html("↑↑");
				$("tr[pid='"+$(this).attr("action")+"']").show();
			}
		});
		$("#menuName").unbind("keydown").bind("keydown",
			function (event){
				if(event.keyCode==13){
					event.stopPropagation();
					event.preventDefault();
					$("#btnNext").trigger("click");
					$(this).trigger("focus");	
				}
		});
		var menuName="";
		var focusIndex = 0;
		var focusTd=null;
		$("#btnNext").unbind("click").click(function(){
			var value = $("#menuName").val();
			if(menuName==value){
				if(value=="")
					return;
				//下一个
				if(focusTd!=null && focusTd.size()>0){
					focusIndex++;
					if(focusIndex==focusTd.size())//超出长度，选中第一个
						focusIndex=0;
					focusTdSearch($(focusTd[focusIndex]));
				}
			}else{
				$("td.tdSearch").removeClass("tdSearch");
				if(value==""){//无输入，清空
					menuName="";
					focusIndex = 0;
					focusTd=null;
					return;
				}
				focusTd = $("td[menu^='"+value+"']").addClass("tdSearch");
				focusIndex = 0;
				menuName=value;
				if(focusTd.size()>0){//默认选中第一个
					focusTdSearch($(focusTd[focusIndex]));
				}
			}
		});
	});
	function focusTdSearch(focusTd){
		var tr = focusTd.parents("tr:first");
		if(focusTd.is(":hidden"))
			$("tr[mid='"+tr.attr("pid")+"']:first span[action]:first").click();
		var top = 0;
		var prevTd = tr.prev();
		var isFirst=false;
		while(!isFirst){
			if(prevTd.size()==1){
				if(prevTd.is(":visible"))
					top+=prevTd.height();
				prevTd=prevTd.prev();
			}else{
				isFirst=true;
			}
		}
		$("#divScroll").scrollTop(top);
	}

</script>

</head>
<body>
<form action="<%=path%>/roleauthority/roleauthority_modify_managerAction.action" method="post" id="saveForm">
<table width="98%" align="center" border="0" cellpadding="4" cellspacing="1" bgcolor="#F1F1F1">
  <tr id="map">
    <td><!--<div class="info_right_tit">*<span><a style="font-size:12px; color:#999;" href="#">*</a><a style="font-size:12px; color:#999;" href="<%=path %>/default.action" target="_top">-首页</a></span></div>--></td>
  </tr>
  <tr id="searchPanel">
    <td style="background-color:#F6F6F6;padding:5px;padding-bottom:0px;border-bottom:1px #666666 dashed;">
    <table cellpadding="0" cellspacing="0" width="100%">
    	<tr>
    		<td width="100" align="right">用户角色：</td>
    		<td width="180">
				<select id="roleSelect" name="roleId" onchange="changeSelect()">
		    		<option value="0"></option>
		    		<c:forEach items="${roleList}" var="role">
		    			<option value="${role.roleId}">${role.roleName}</option>
		    		</c:forEach>
		    	</select>
    		</td>
    		<td width="100" align="right">菜单名称：</td>
    		<td width="180">
				<input type="text" id="menuName" class="info_right_input" maxlength="15" />
    		</td>
    		<td width="150"><input class="btn" type="button" id="btnNext" value="下一个" /></td>
	        <td align="right" style="padding-right:30px;">
	        	<c:if test='${fn:contains(authorityCode,",0001,") or fn:contains(authorityCode,",0003,")}'><input type='button' class="btn btn-primary" id="btnSave" onclick="save();" value='保存' /></c:if>
	        </td>
    	</tr>
    </table>
    </td>
    </tr>
    <tr>
    	<td>
    		<div id="divScroll" style="overflow:auto;display:none;">
	    		<table cellpadding="0" cellspacing="0" width="100%" style="TABLE-LAYOUT: fixed;">
	    			<c:forEach items="${menuList}" var="menu">
    					<tr height="30" mid="${menu.menuId}" pid="${menu.parentMenuId}" onMouseMove="javascript:this.bgColor='#f1f1f1';" onMouseOut="javascript:this.bgColor='#FFFFFF';">
	    				<c:if test="${menu.parentMenuId eq 0}" >
    						<td title="顶级菜单" menu="${menu.menuName}" style="word-WRAP: break-word;width:250px;padding-left:10px;"><span style="color:#FF0000;padding-left:60px;">${menu.menuName}</span></td>
	    				</c:if>
	    				<c:if test="${menu.parentMenuId ne 0}">
    						<td title="二级菜单" menu="${menu.menuName}" style="word-WRAP: break-word;width:250px;padding-left:10px;"><span style="color:#FFA500;padding-left:100px;">${menu.menuName}</span></td>
	    				</c:if>
						    <td align="left">
					    		<c:forEach items="${menuAuthorityList}" var="ma">
						    	<c:if test="${ ma.menu.menuId eq menu.menuId}">
						    		<input id="${ma.menu.menuId}n${ma.authority.authorityId}" type="checkbox" name="checkbox" code="${ma.authority.authorityNo}" onclick="checkboxSelect('${ma.menu.menuId}','${ma.authority.authorityNo}',this);" value="${ma.menu.menuId},${ma.authority.authorityId}" />${ma.authority.authorityName}
						    	</c:if>
							    </c:forEach>
						    </td>
					   </tr>
				   </c:forEach>
	    		</table>
    		</div>
    	</td>
    </tr>
</table>
</form>
	<form action="<%=path%>/roleauthority/roleauthority_save_managerAction.action" method="post" style="display: none;" id="refreshForm" name="refreshForm">
		<input type="hidden" name="menuAuthorityRoleId" class="hiddenRoleId" value="${menuAuthority4save.role.roleId}"/>
		<input type="hidden" name="menuAuthorityString" class="hiddenString" value="${menuAuthorityString}"/>
		<input type="hidden" class="currentMenuId" name="currentMenuId" value="${currentMenuId}"/>
	</form>
</body>
</html>
